/**
 * jQuey右键菜单
 * @author liujhc <liujhc@si-tech.com.cn>
 * 用法1：
 * $(document).contextMenu([{text:'菜单一',click:function(){alert(this.text)}}]);
 * 用法2：
 * $(document).contextMenu(function(){
 *		var items=[];
 *		var item={
 *			text:'菜单一',
 *			click:function($target){//回调函数的this代表item对象本身，$target是右键点击的元素的jquery包装
 *				alert(this.text)
 *			}
 *		};
 * });
 */
(function($){
    var $menu, $shadow, topWin = window;
    try { // 取得同域的最顶层window
        while (topWin.parent != topWin && topWin.parent.document) {
            topWin = topWin.parent;
        }
    } catch (e) {
    }
	var defaults = {
		menuStyle: {
			listStyle: 'none',
			padding: '1px',
			margin: '0px',
			backgroundColor: '#fff',
			border: '1px solid #999',
			width: '100px'
		},
		itemStyle: {
			margin: '0px',
			color: '#000',
			display: 'block',
			cursor: 'default',
			padding: '3px',
			'text-align':'left',
			border: '1px solid #fff',
			backgroundColor: 'transparent'
		},
		itemHoverStyle: {
			border: '1px solid #0a246a',
			backgroundColor: '#b6bdd2'
		},
		eventType:'contextmenu'
	}
	var hide=function(){
		$menu.hide();
		$shadow.hide();
	}
	var hideAll=function(){//关闭所有的右键菜单
		try{
			if(topWin.contextMenuQueue){
				$.each(topWin.contextMenuQueue,function(){
					this.hide();
				});
			}
		}catch(e){
			console.log(e);
		}finally{
			hide();
		}
	}
	var dispaly=function(list, e, btn){
		hideAll();
		var $target=$(this);
		var $content=$('<ul></ul>').css(defaults.menuStyle);
        $.each(list, function () {
            if (this == "separator") {
                $('<li><hr/></li>').css({margin: "-2px 0"}).appendTo($content);
                return true;
            }
            if (this.hidden === true) {
                return true;
            }
            $('<li>'+this.text+'</li>')
			.data("item-data",this)
			.css(defaults.itemStyle)
			.click(function(){
				var itemData=$(this).data("item-data");
				if($.isFunction(itemData.click)){
					itemData.click.call(itemData,$target);
				}
			})
            .mouseenter(function(){
                var itemData=$(this).data("item-data");
                if($.isFunction(itemData.mouseenter)){
                    itemData.mouseenter.call(itemData,$target,this);
                }
            })
            .mouseleave(function(){
                var itemData=$(this).data("item-data");
                if($.isFunction(itemData.mouseleave)){
                    itemData.mouseleave.call(itemData,$target,this);
                }
            })
            .hover(function(){
				$(this).css(defaults.itemHoverStyle);
			}, function(){
				$(this).css(defaults.itemStyle);
			}).appendTo($content);
		});
		$content.find('img').css({
			verticalAlign:'middle',
			paddingRight:'2px'
		});
		$menu.empty().append($content);
		var bodyW = $("body").width(), bodyH=Math.max(document.documentElement.clientHeight,document.body.offsetHeight);
		var menuW = $menu.width(), menuH=$menu.height();
        var cX=e.pageX, cY=e.pageY;
        if($.isFunction(window.offset)){
            var offset = window.offset();
            cX+=offset.left||0;
            cY+=offset.top||0;
        }
		var left=(bodyW-cX>menuW|| cX<menuW)?cX:(cX-menuW), top=(bodyH-cY>menuH || cY<menuH)?cY:(cY-menuH)
		$menu.css({
			'left':left,
			'top':top
		}).show();
		$shadow.css({
			width:menuW,
			height:menuH,
			left:left+2,
			top:top+2
		}).show();
        // 禁止menu和shadow
        $($menu).add($shadow).bind('contextmenu',function () {
            return false;
        }).add(document).add(topWin.document).one('click', hideAll);//当出现点击事件时，隐藏右键菜单
	}
	$.fn.contextMenu=function(setting){
		if(arguments.length>1){//兼容旧方法
			setting={
				items:arguments[0],
				type:arguments[1],
				button:arguments[2]
			};
		}
		if(!$menu){
			$menu = $('<div class="jqContextMenu_menu"></div>')
			.hide().css({
				position:'absolute',
				zIndex:'500'
			})
			.appendTo('body').bind('click', function(e) {
				e.stopPropagation();
			});
		}
		if(!$shadow){
			$shadow = $('<div class="jqContextMenu_shadow"></div>').css({
				backgroundColor:'#000',
				position:'absolute',
				opacity:0.2,
				zIndex:499
			})
			.appendTo('body').hide();
        }
        //如果有可访问的父页面，将菜单放入父页面中
        if (topWin != window && window.offset) {
            $(topWin.document.body).find(".jqContextMenu_menu,.jqContextMenu_shadow").remove();
            $($menu).add($shadow).appendTo(topWin.document.body);
        }
		try{//将所有的右键菜单的关闭方法放入top队列中，以便关闭其他iframe里的右键菜单
			if(!topWin.contextMenuQueue){
				topWin.contextMenuQueue=new topWin.Array();
			}
			topWin.contextMenuQueue.push({
				hide:hide
			});
		}catch(e){
			console.log(e)
		}
		$(this).each(function(){
			var list = $.isFunction(setting.items)?setting.items.call(this):setting.items;
			if(list && $.isArray(list) && list.length>0){
                $.each(list, function () {
                    if (this.id && isNaN(this.id)) {
                        list[this.id] = this;
                    }
                });
				var $target = $(this);
				if(setting.button){
					$target = $(setting.button).appendTo(this).css("cursor","pointer");
				}
				$target.bind(setting.type||defaults.eventType, function(e) {
					if(setting.onOpen&&$.isFunction(setting.onOpen)){
						if(false===setting.onOpen.call(this, list)){
							return false;
						}
					}
					var target=this;
					if(setting.button){
						target=$(this).parent()
					}
					dispaly.call(target, list, e, setting.button);
					return false;
				});
			}
		});
		return this;
	}
})(jQuery);